<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表:优秀实践，copy domain修改列表
        :data就是绑定一个数组  elementUI底层封装了v-for循环遍历这个数组，来展示数据
    -->
    <el-table :data="pageData.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="petType.name" label="宠物类别" width="150" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="200" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺"  width="150" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==0">已下架</span>
          <span style="color: red" v-else="scope.row.state==1">已上架</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" v-perm="'employee:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="query.currentPage" :page-size="query.pageSize" :total="pageData.total" style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 模态框 name: null,
        saleprice: null,
        costprice: null,
        resources: null,
        typeId: null,
        note: null,
        adoptNotice: null,
        intro: null,-->
    <el-dialog :title="title" :visible.sync="employeeFormVisible" :close-on-click-modal="false">
      <el-form :model="petForm" label-width="80px" :rules="petFormRules" ref="petForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="petForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="petForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="petForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物类别" prop="petTypeId">
          <el-cascader v-model="petForm.typeId"
                       :options="petTypeTree"
                       :props="{
                        checkStrictly: true,
                        label:'name',
                        value:'id',
                        expandTrigger: 'hover'
                        }"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="宠物图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/upload"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="petForm.note" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="领养须知">
          <quill-editor v-model="petForm.adoptNotice" :options="quillConfig" auto-complete="off"></quill-editor>
        </el-form-item>
        <el-form-item label="宠物详情">
          <quill-editor v-model="petForm.intro" :options="quillConfig" auto-complete="off"></quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="employeeFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="employeeLoading">保存</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import {quillEditor} from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import quillConfig from '../../common/js/quill-config'
export default {
  name: "Pet",
  //自定义局部组件
  components:{
    quillEditor
  },
  data(){
    return {
      quillConfig,    //定义属性
      title:'',
      pageData:{
        total:0,//分页条
        list:[]//数据表格
      },
      petTypeTree:[],     //宠物类别树形结构数据
      query:{
        keyword:'',
        currentPage:1,//分页条
        pageSize:10 //分页条
      },
      listLoading: false,
      sels: [],//列表选中列
      employeeFormVisible: false,//编辑界面是否显示
      employeeLoading: false,
      petForm:{
        id: null,
        name: null,
        saleprice: null,
        costprice: null,
        resources: null,
        typeId: null,
        note: null,
        adoptNotice: "",
        intro: "",
      },
      petFormRules:[],
      fileList:[],      //文件数组
      imgUrlList:[],      //宠物图片地址数组
    }
  },
  methods:{
    selsChange(sels){
      this.sels = sels;
    },
    //获取用户列表
    getPets() {
      this.listLoading = true; //加载条
      this.$http.post("/pet/list",this.query)
          .then(result => {
            this.pageData = result.data;
            this.listLoading = false; //去除加载条
          })
          .catch(result=>{
            alert("抱错了")
          })
    },
    handleAdd(){
      this.title = "新增宠物"
      this.employeeFormVisible = true
    },
    handleCurrentChange(pageNumer){
      this.query.currentPage = pageNumer
      this.getPets();
    },
    search(){
      this.query.currentPage = 1
      this.getPets();
    },
    getPetTypeTree(){
      this.$http.get("/petType/tree").then(res => {
        this.petTypeTree = res.data.resultObj;
      })
    },
    //上传成功：response响应消息   file本次上传的文件对象   fileList文件数组对象
    handleSuccess(response, file, fileList){
      console.log(response)
      console.log(file)
      console.log(fileList)
      console.log("=====================================")
      //给petForm的resources属性赋值，然后提交表单时才能保存这个图片地址
      //思考：宠物只有一张图片吗？  不止一张，多张图片地址之间使用逗号隔开
      this.imgUrlList.push(response.resultObj)  //AjaxResult
      this.petForm.resources = this.imgUrlList.join(",");  //join就是把数组中的元素使用指定字符拼接成长字符串，这样就不会有多余的逗号了
    },
    //删除图片  自己完成
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    save(){
      this.$refs.petForm.validate((valid) => {
        if (valid) {
          //组装petdetail
          this.petForm.petDetail = {
            adoptNotice: this.petForm.adoptNotice,
            intro: this.petForm.intro,
          }
          //获取宠物类别级联框数组的最后一位  [1,5]
          this.petForm.typeId = this.petForm.typeId[this.petForm.typeId.length - 1]

          this.$http.put("/pet", this.petForm).then(res => {
            let {success,message,resultObj} = res.data
            if(success){
              this.employeeFormVisible = false
              this.$message.success("新增宠物成功")
              //重新加载数据
              this.getPets();
            }else{
              this.$message.error("新增宠物失败")
            }
          })
        }
      })
    },
    handleEdit(index, row){
      this.petForm = Object.assign({}, row);
      this.title = "修改宠物"

      //回显宠物类别级联框  根据当前宠物的宠物类别id去查询类别表  [1,5]
      this.$http.get("/petType/" + row.typeId).then(res => {
        let petType = res.data
        //组装数组  [1,5]  如果是不确定有多少级类别的话，需要添加一个path字段，记录从最顶级类别的id 一直到它的自己的id
        this.petForm.typeId = [petType.pid, petType.id]
      })

      //回显el-upload文件上传框
      let resources = this.petForm.resources;
      if(resources){
        //以逗号拆分字符串 得到数组
        this.imgUrlList = resources.split(",")
        this.fileList = []    //先清空一下
        this.imgUrlList.forEach(imgUrl => {
          this.fileList.push({
            name: imgUrl.substr(imgUrl.lastIndexOf("/")+1),
            url: this.fastdfsUrl+imgUrl
          })
        })
      }

      //回显宠物领养须知和宠物详情  富文本编辑  通过宠物id去查询宠物详情表得到数据
      this.$http.get("/petDetail/findByPetId/"+this.petForm.id).then(res => {
        this.petForm.adoptNotice = res.data.adoptNotice
        this.petForm.intro = res.data.intro
        this.employeeFormVisible = true
      })
    }
  },
  mounted() {
    this.getPets();
    this.getPetTypeTree();
  }
}
</script>

<style scoped>

</style>